using System.Collections;
using System.Collections.Generic;
using QFramework;
using UnityEngine;
using UnityEngine.U2D;
using System;

namespace HareGame
{
    [MonoSingletonPath("GameEntry/AtlasManager")]
    public class AtlasManager : MonoBehaviour_Ex, ISingleton
    {
        public List<AtlasData> AtlasDatas = new List<AtlasData>();

        Dictionary<string, Sprite> _cache = new Dictionary<string, Sprite>();

        public void OnSingletonInit()
        {
            foreach (AtlasType ID in Enum.GetValues(typeof(AtlasType)))
            {
                SpriteAtlas atlas = m_ResLoader.LoadSync<SpriteAtlas>(ID.ToString());
                AtlasDatas.Add(new AtlasData(ID, atlas));
            }
        }

        /// <summary>
        /// 定义单例
        /// </summary>
        public static AtlasManager Instance
        {
            get { return MonoSingletonProperty<AtlasManager>.Instance; }
        }

        public Sprite LoadSprite(AtlasType atlas, string name)
        {
            if (_cache.ContainsKey(name))
            {
                return _cache[name];
            }

            foreach (var v in AtlasDatas)
            {
                if (v.Type == atlas)
                {
                    Sprite sprite = v.Atlas.GetSprite(name);
                    if (!_cache.ContainsKey(name))
                    {
                        _cache.Add(name, sprite);
                    }
                    return sprite;
                }
            }
            LogKit.E("找不到图集:" + atlas.ToString() + "或者名为:" + name + "的图片");
            return null;
        }
    }

    public enum AtlasType
    {
        IconAtlas,
        RewardAtlas,
        UIAtlas,
    }

    [Serializable]
    public class AtlasData
    {
        public AtlasType Type;
        public SpriteAtlas Atlas;

        public AtlasData(AtlasType type, SpriteAtlas atlas)
        {
            Type = type;
            Atlas = atlas;
        }
    }
}